﻿using Azure;
using Flurl.Http;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HYHY_Core.Enums;
using HYHY_Core.Tool.Token;
using HYQY_Core.Entities.Utils;
using HYQY_Core.Entities.Ware;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using static HYQY_App.Tool.Image.ImageDto;

namespace HYQY_App.Tool.Image
{

    /// <summary>
    /// 图片工具服务-公共（调用方式：）
    /// await InsertImagesAsync(input.MainImages, input.WareCode, "Main", user.UserName);
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.Tool, Name = "ImageToolService")]
    public class ImageService : IDynamicApiController, ITransient, IImageService
    {
        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        private readonly HttpClient _httpClient;
        private readonly string _apiKey; // 从 ImgBB 后台获取的 API Key

        /// <summary>
        /// 构造函数
        /// </summary>
        public ImageService(ISqlSugarClient db, HttpClient httpClient, IConfiguration configuration)
        {
            _httpClient = httpClient;
            _apiKey = configuration["ImgBb:ApiKey"]; // 配置到 appsettings.json
            _db = db;
        }

        /// <summary>
        /// 上传图片到ImgBB
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <param name="type">图片类型</param>
        /// <returns></returns>
        public async Task<ImgBBResponse> UploadImageImgBB(IFormFile file, string type, string wareCode)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限");

            if (file == null || file.Length == 0) throw Oops.Bah("请选择有效的图片文件");

            try
            {
                // 图片重命名 拼接 type + wareCode + 原文件名后缀（保留格式）
                var originalExt = Path.GetExtension(file.FileName);
                var fileFileName = $"{type}_{wareCode}_{Guid.NewGuid()}{originalExt}";

                using var stream = file.OpenReadStream();

                // 调用接口时，使用简化模型接收响应
                var response = await new FlurlRequest("https://api.imgbb.com/1/upload")
                    .PostMultipartAsync(mp => mp
                        .AddString("key", _apiKey)
                        .AddFile("image", stream, fileFileName))
                    .ReceiveJson<ImgBBResponse>();

                // 直接获取需要的 url
                if (response?.success == true && response.data != null)
                {
                    string imageUrl = response.data.url; // 只使用这个字段
                                                         // 后续逻辑...
                }
                else
                {
                    throw Oops.Bah("图片上传失败");
                }

                if (response == null || response.data == null)
                    throw Oops.Bah("图片上传异常，响应数据为空=>【UploadImageImgBB】");

                return response;
            }
            catch (FlurlHttpException ex)
            {
                throw Oops.Bah("图片上传失败", ex);
            }
        }

        /// <summary>
        /// 上传图片到GitHub仓库
        /// </summary>
        /// <param name="imageStream">图片流</param>
        /// <param name="fileName">图片文件名（如images/xxx.jpg）</param>
        /// <returns>图片访问链接</returns>
        //public async Task<string> UploadImageAsync(Stream imageStream, string fileName)
        //{
        //    // 1. 读取图片并转为Base64
        //    byte[] imageBytes;
        //    using (var ms = new MemoryStream())
        //    {
        //        await imageStream.CopyToAsync(ms);
        //        imageBytes = ms.ToArray();
        //    }
        //    string base64Image = Convert.ToBase64String(imageBytes);

        //    // 2. 构建GitHub API请求
        //    var apiUrl = $"https://api.github.com/repos/{_owner}/{_repo}/contents/{fileName}";
        //    var client = new HttpClient();
        //    client.DefaultRequestHeaders.UserAgent.TryParseAdd("HttpClient"); // GitHub API要求设置User-Agent
        //    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("token", _accessToken);

        //    // 3. 准备请求体（包含Base64图片和提交信息）
        //    var requestBody = new
        //    {
        //        message = "Upload image via API", // 提交说明
        //        content = base64Image,
        //        branch = "main"
        //    };
        //    var json = JsonSerializer.Serialize(requestBody);
        //    var content = new StringContent(json, Encoding.UTF8, "application/json");

        //    // 4. 发送请求
        //    var response = await client.PutAsync(apiUrl, content);
        //    if (response.IsSuccessStatusCode)
        //    {
        //        // 5. 解析响应，返回图片链接
        //        var responseJson = await response.Content.ReadAsStringAsync();
        //        var result = JsonSerializer.Deserialize<dynamic>(responseJson);
        //        return result.content.download_url; // 直接下载链接
        //    }

        //    return null;
        //}


        /// <summary>
        /// 批量添加图片
        /// </summary>
        /// <param name="imageUrls">图片url数组</param>
        /// <param name="wareCode">商品编码</param>
        /// <param name="type">图片类型</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        // 1. 提取公共方法，消除重复代码
        public async Task InsertImagesAsync(List<string> imageUrls, string wareCode, string type, string userName)
        {
            // 2. 批量创建实体（减少多次实例化的开销）
            var images = imageUrls.Select(url => new Images
            {
                Code = wareCode,
                CreateMan = userName,
                CreateTime = DateTime.Now,
                Id = Guid.NewGuid().ToString("N"),
                Type = type,
                IsDelete = false,
                Url = url
            }).ToList();

            // 3. 批量插入（减少数据库交互次数，大幅提升性能）
            await _db.Insertable(images).ExecuteCommandAsync();
        }

        /// <summary>
        /// 批量删除图片
        /// </summary>
        /// <param name="imageUrls">图片url数组</param>
        /// <param name="wareCode">商品编码</param>
        /// <param name="type">图片类型</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        // 1. 提取公共方法，消除重复代码
        public async Task<ResponseStatus> DeleteImages(DeleteImagesAsyncInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey() ?? throw Oops.Bah("未登录，无权限访问接口");
            var image = await _db.Queryable<Images>()
              .Where(it => it.Code == input.WareCode && it.Type == input.Type && it.Url == input.ImageUrl)
              .FirstAsync();

            if (image != null)
            {
                image.IsDelete = true;
                image.UpdateTime = DateTime.Now;
                image.UpdateMan = user.UserName;

                int count = await _db.Updateable(image).WhereColumns(it => it.Id)
                    .UpdateColumns(it => new
                    {
                        it.IsDelete,
                        it.UpdateTime,
                        it.UpdateMan
                    })
                    .ExecuteCommandAsync();

                if (count < 1) throw Oops.Bah("删除失败");

                return new ResponseStatus { Message = "删除成功", StatusCode = 200 };
            }
            return null;
        }
    }
}
